package com.mgy.mock;

import java.io.*;
import java.nio.file.Files;
import java.util.function.Consumer;

/**
 * xxx
 *
 * @author maguoyong
 * @date 2021/1/5
 */
public abstract class AbstractFileReadWrite {

    protected void writeFile(String content, String savePath) {
        try {
            File file = new File(savePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(file.getAbsoluteFile()))) {
                writer.write(content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void appendWriteFile(String content, String savePath) {
        try {
            File file = new File(savePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(file.getAbsoluteFile(), true))) {
                writer.write(content);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void readFile(String savePath, Consumer<String> consumer) {
        try {
            File file = new File(savePath);
            if (!file.exists()) {
                throw new RuntimeException("文件不存在");
            }
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(file.toPath())))) {
                String line = null;
                while ((line = reader.readLine()) != null) {
                    consumer.accept(line);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    protected String readFile(String savePath) {
        try {
            File file = new File(savePath);
            if (!file.exists()) {
                throw new RuntimeException("文件不存在");
            }
            StringBuilder stringBuilder = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(file.toPath())))) {

                String line = null;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
            }
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    protected boolean isExist(String path) {
        File file = new File(path);
        if (file.exists()) {
            return true;
        }
        return false;
    }

}
